<template>
  <div class="contract-approval">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="合同编号">
          <el-input v-model="searchForm.contractNo" placeholder="请输入合同编号" clearable />
        </el-form-item>
        <el-form-item label="合同名称">
          <el-input v-model="searchForm.contractName" placeholder="请输入合同名称" clearable />
        </el-form-item>
        <el-form-item label="合同类型">
          <el-select v-model="searchForm.contractType" placeholder="请选择合同类型" clearable>
            <el-option
              v-for="item in contractTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column prop="contractNo" label="合同编号" width="150" />
        <el-table-column prop="contractName" label="合同名称" min-width="200" />
        <el-table-column prop="contractTypeName" label="合同类型" width="120" />
        <el-table-column prop="totalAmount" label="合同金额" width="120">
          <template #default="scope">
            {{ formatMoney(scope.row.totalAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="signedDate" label="签订日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.signedDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="startDate" label="开始日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.startDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="endDate" label="结束日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.endDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="statusName" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.statusName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="success" size="small" @click="handleApprove(scope.row)" v-if="scope.row.status === 1">
              审批通过
            </el-button>
            <el-button type="danger" size="small" @click="handleReject(scope.row)" v-if="scope.row.status === 1">
              审批拒绝
            </el-button>
            <el-button type="primary" size="small" @click="handleView(scope.row)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 审批拒绝对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="审批拒绝"
      width="500px"
    >
      <el-form :model="rejectForm" :rules="rejectRules" ref="rejectFormRef" label-width="80px">
        <el-form-item label="拒绝原因" prop="reason">
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmReject">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 合同详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="合同详情"
      width="80%"
      :close-on-click-modal="false"
    >
      <div v-if="contractDetail" class="contract-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="合同编号">{{ contractDetail.contractNo }}</el-descriptions-item>
          <el-descriptions-item label="合同名称">{{ contractDetail.contractName }}</el-descriptions-item>
          <el-descriptions-item label="合同类型">{{ contractDetail.contractTypeName }}</el-descriptions-item>
          <el-descriptions-item label="合同金额">{{ formatMoney(contractDetail.totalAmount) }}</el-descriptions-item>
          <el-descriptions-item label="签订日期">{{ formatDate(contractDetail.signedDate) }}</el-descriptions-item>
          <el-descriptions-item label="开始日期">{{ formatDate(contractDetail.startDate) }}</el-descriptions-item>
          <el-descriptions-item label="结束日期">{{ formatDate(contractDetail.endDate) }}</el-descriptions-item>
          <el-descriptions-item label="合同状态">
            <el-tag :type="getStatusTagType(contractDetail.status)">{{ contractDetail.statusName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(contractDetail.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(contractDetail.updateTime) }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ contractDetail.remark || '无' }}</el-descriptions-item>
        </el-descriptions>

        <!-- 合同明细 -->
        <div v-if="contractDetail.contractItems && contractDetail.contractItems.length > 0" class="contract-items">
          <h3>合同明细</h3>
          <el-table :data="contractDetail.contractItems" border stripe>
            <el-table-column prop="productName" label="产品名称" min-width="200" />
            <el-table-column prop="specification" label="规格型号" width="150" />
            <el-table-column prop="unitName" label="单位" width="80" />
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="unitPrice" label="单价" width="120">
              <template #default="scope">
                {{ formatMoney(scope.row.unitPrice) }}
              </template>
            </el-table-column>
            <el-table-column prop="totalAmount" label="小计" width="120">
              <template #default="scope">
                {{ formatMoney(scope.row.totalAmount) }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="200" />
          </el-table>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { contractApi } from '@/api/contract/contract'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: "contract_approval",
  data() {
    return {
      // 搜索表单
      searchForm: {
        contractNo: '',
        contractName: '',
        contractType: ''
      },
      // 表格数据
      tableData: [],
      // 加载状态
      loading: false,
      // 分页信息
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },
      // 合同类型列表
      contractTypeList: [],
      // 审批拒绝对话框
      rejectDialogVisible: false,
      // 拒绝表单
      rejectForm: {
        reason: ''
      },
      // 拒绝表单验证规则
      rejectRules: {
        reason: [
          { required: true, message: '请输入拒绝原因', trigger: 'blur' }
        ]
      },
      // 当前操作的合同
      currentContract: null,
      // 合同详情对话框
      detailDialogVisible: false,
      // 合同详情数据
      contractDetail: null
    }
  },
  mounted() {
    this.initData()
  },
  methods: {
    // 初始化数据
    async initData() {
      await this.getContractTypeList()
      this.loadTableData()
    },

    // 获取合同类型列表
    async getContractTypeList() {
      try {
        const res = await contractApi.getContractTypeList()
        if (res.code === 200) {
          this.contractTypeList = res.data
        }
      } catch (error) {
        console.error('获取合同类型列表失败:', error)
      }
    },

    // 加载表格数据
    async loadTableData() {
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          current: this.pagination.current,
          size: this.pagination.size,
          status: 1 // 只查询待审批状态的合同
        }
        const res = await contractApi.getContractPage(params)
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        }
      } catch (error) {
        console.error('加载表格数据失败:', error)
        ElMessage.error('加载数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadTableData()
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        contractNo: '',
        contractName: '',
        contractType: ''
      }
      this.handleSearch()
    },

    // 审批通过
    async handleApprove(row) {
      try {
        await ElMessageBox.confirm('确定要审批通过该合同吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const res = await contractApi.approveContract(row.id)
        if (res.code === 200) {
          ElMessage.success('审批通过成功')
          this.loadTableData()
        } else {
          ElMessage.error(res.message || '审批失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('审批失败:', error)
          ElMessage.error('审批失败')
        }
      }
    },

    // 审批拒绝
    handleReject(row) {
      this.currentContract = row
      this.rejectForm.reason = ''
      this.rejectDialogVisible = true
    },

    // 确认拒绝
    async confirmReject() {
      try {
        await this.$refs.rejectFormRef.validate()
        
        const res = await contractApi.rejectContract(this.currentContract.id, this.rejectForm.reason)
        if (res.code === 200) {
          ElMessage.success('审批拒绝成功')
          this.rejectDialogVisible = false
          this.loadTableData()
        } else {
          ElMessage.error(res.message || '审批拒绝失败')
        }
      } catch (error) {
        console.error('审批拒绝失败:', error)
      }
    },

    // 查看详情
    async handleView(row) {
      try {
        const res = await contractApi.getContractById(row.id)
        if (res.code === 200) {
          this.contractDetail = res.data
          this.detailDialogVisible = true
        } else {
          ElMessage.error(res.message || '获取合同详情失败')
        }
      } catch (error) {
        console.error('获取合同详情失败:', error)
        ElMessage.error('获取合同详情失败')
      }
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadTableData()
    },

    // 当前页变化
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadTableData()
    },

    // 格式化金额
    formatMoney(amount) {
      if (!amount) return '0.00'
      return Number(amount).toFixed(2)
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return new Date(date).toLocaleDateString()
    },

    // 格式化日期时间
    formatDateTime(date) {
      if (!date) return ''
      return new Date(date).toLocaleString()
    },

    // 获取状态标签类型
    getStatusTagType(status) {
      const statusMap = {
        0: 'info',    // 草稿
        1: 'warning', // 待审批
        2: 'success', // 生效
        3: 'success', // 完成
        4: 'danger'   // 终止
      }
      return statusMap[status] || 'info'
    }
  }
}
</script>

<style scoped>
.contract-approval {
  padding: 20px;
}

.search-area {
  background: #fff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.dialog-footer {
  text-align: right;
}

.contract-detail .el-descriptions {
  margin-bottom: 20px;
}

.contract-detail .el-descriptions-item__label {
  font-weight: bold;
}

.contract-items h3 {
  margin-top: 0;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}
</style>
